package com.ylt.juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SaleTicketDemo02 {
    public static void main(String[] args) {
        Ticket02 ticket = new Ticket02();
        new Thread(() -> {
            for (int i = 0; i < 60; i++) {
                ticket.sale();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 60; i++) {
                ticket.sale();
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 60; i++) {
                ticket.sale();
            }
        }, "C").start();
    }
}


// 资源类 OOP
class Ticket02 {
    //属性，方法
    private int ticketNum = 50;

    //1.new ReentrantLock();
    Lock lock = new ReentrantLock();


    //买票方式
    public void sale() {

        //2.lock.lock();加锁
        lock.lock();

        try {

            if (ticketNum > 0) {
                System.out.println(Thread.currentThread().getName()
                        + "卖出了" + (51 - ticketNum--) + "票，剩余：" + ticketNum);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //3.解锁
            lock.unlock();
        }
    }
}
